/*

GFormIt-Docs.gs (Google Apps Script; Apache2 license)
    apache.org/licenses/LICENSE-2.0.html

created Feb 2014 for edcode.org (updated Oct 2014)

*/

function onOpen(e) {
    // only add menu if Add-on enabled
    if (e && e.authMode == ScriptApp.AuthMode.NONE) {} else { _createMenu(); }
}

function _createMenu() {
    DocumentApp.getUi()
        .createAddonMenu()
        .addItem('Generate Form', 'docCreateForm')
        .addSeparator()
        .addItem('About GFormIt', 'aboutGFormIt')
        .addToUi();
}

function onInstall(e) {
    onOpen(e);
}

function onEnable(e) {
    onOpen(e);
}

function aboutGFormIt() {
    DocumentApp.getUi().alert("\
      GFormIt is a time-saving Google Docs Add-on that auto-generates\
      Google Forms. Teachers & other users can create exams/quizzes or\
      polls quickly and hassle-free based on the raw questions placed\
      in a Google Doc.\n\nOptionally-provided answers are submitted as\
      the first response (row) in the auto-generated Google Sheet so\
      users have the option of using Flubaroo (a teacher tool that\
      grades assessments), providing that first row as the 'answer\
      key.' To learn more about GFormIt or Flubaroo, visit edcode.org.");
}

function createForm(values) {
    // get handle to this Doc; create & name Form
    var app = DocumentApp;
    var doc = app.getActiveDocument();
    var form_name = doc.getName();
    var form = FormApp.create(form_name).setTitle(form_name);

    // create Sheet for responses and create one (a response)
    var ss = SpreadsheetApp.create(form_name + " RESPONSES");
    form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
    var frsp = form.createResponse();

    // process form questions (and possibly answers)
    for (var i in values) {
        var len = values[i].length      // number of "answers" per Q
        var question = values[i][0];    // save question text
        if (question == null || question[0] == "" || question[0] == "#") {
            continue;
        }

        // Q but no A; no response
        if (len == 1) {
            form.addParagraphTextItem().setTitle(question);
        // single answer; add to response
        } else if (len == 2) {
            var answer = values[i][1];
            var item = form.addTextItem().setTitle(question);
            frsp.withItemResponse(item.createResponse(answer));
        }
    }

    frsp.submit(); // submit response (possible answer key for Flubaroo)
    ss.deleteSheet(ss.getSheetByName('Sheet1'));    // remove extra sheet

    // email payload
    var subj = "'" + form_name + "' Form & Sheet generated by GFormIt";
    var msg = "GFormIt has generated the following for you on Google Drive:\n\
    * a Google Form: '" + form_name + "'\n\
    * a Google Sheet: '" + form_name + " RESPONSES'\n\n\
Any answers provided were submitted as the first 'answer', \
giving you the option of using the Flubaroo grading tool.\n";
    var links = "\nLinks for your convenience:\n\
    * Google Form (editable version): " + form.getEditUrl() + "\n\n\
    * Google Form (live version): " + form.getPublishedUrl() + "\n\n\
    * Response Sheet: " + ss.getUrl() + "\n\n\
    * Form response analytics: " + form.getSummaryUrl() + "\n\n\
Happy Forming!\n\
-The GFormIt team";

    // send email and bring up completion dialog
    var userEmail = Session.getEffectiveUser().getEmail();
    MailApp.sendEmail(userEmail, subj, msg + links);
    var ui = app.getUi();
    ui.alert(msg + "\nA summary email with links has been sent to '" + userEmail + "'");
}

// parse data out of Google Doc & process
function docCreateForm() {
    var doc = DocumentApp.getActiveDocument();
    var text = doc.getBody().getText();
    var lines = text.split(/[\n\r]/);
    var body = [];
    var row = [];

    for (var line in lines) {
        if (lines[line] == "") {
            body.push(row);
            row = []; // reset to empty row for next Q
        } else {
            row.push(lines[line].trim());
        }
    }
    body.push(row); // add last row
    createForm(body);
}
